package com.example.cloud.service.impl;

import com.example.cloud.apis.AccountFeignApi;
import com.example.cloud.apis.StorageFeignApi;
import com.example.cloud.entities.Order;
import com.example.cloud.mapper.OrderMapper;
import com.example.cloud.resp.ResultData;
import com.example.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2024-03-29
 * Time: 22:07
 */

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    // 订单
    @Resource
    private OrderMapper orderMapper;
    // 订单微服务通过 openfeign 调用账户微服务
    @Resource
    private AccountFeignApi accountFeignApi;
    // 订单微服务通过 openfeign 调用仓库微服务
    @Resource
    private StorageFeignApi storageFeignApi;



    @GlobalTransactional(name = "ws-create-order", rollbackFor = Exception.class) // 全局事务注解,AT 模式
    @Override
    public void create(Order order) {
        // 全局事务 XID 的检查
        String xid = RootContext.getXID();
        // 1. 新建订单
        log.info("-----> 开始新建订单，xid：" + xid);
        // 订单新建的初始订单状态 state 为 0
        order.setStatus(0);
        int result = orderMapper.insertSelective(order);
        // 插入成功后获取实体对象
        Order orderFromDB = null;
        if (result > 0) {
            // 从 mysql 中获取刚刚插入的订单对象
            orderFromDB = orderMapper.selectOne(order);
            log.info("-----> 新建订单成功，orderFromDB：" + orderFromDB.toString());
            // 2. 扣减库存
            log.info("-----> 开始扣减库存");
            storageFeignApi.decrease(order.getProductId(), order.getCount());
            log.info("-----> 扣减库存成功");
            // 3. 扣减账户
            log.info("-----> 开始扣减账户");
            accountFeignApi.decrease(order.getUserId(), order.getMoney());
            log.info("-----> 扣减账户成功");
            // 4. 修改订单状态，从零到 1,1 代表已经支付
            log.info("-----> 修改订单状态开始");
            orderFromDB.setStatus(1);
            orderMapper.updateByPrimaryKeySelective(orderFromDB);
            log.info("-----> 修改订单状态结束");
            orderFromDB = orderMapper.selectOne(orderFromDB);
            log.info("-----> orderFromDB：" + orderFromDB.toString());
        }
        System.out.println("-----> 结束新建订单，xid：" + xid);
    }
}
